<!--字典类型-->
<template>
    <el-form :model="dictform" ref="dictref" :inline="true" style="text-align: left;">
        <el-form-item label="岗位:" prop="Position_code">
            <el-input placeholder="请输入岗位名称/编号" v-model="dictform.Position_code"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="Position_status">
            <el-select placeholder="请选择" v-model="dictform.Position_status" style="width:200px">
                <el-option :value="0" label="启用"></el-option>
                <el-option :value="1" label="禁用"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="drawer = true">添加</el-button>
        <el-button @click="DeleteAll">删除</el-button>
        <el-button @click="GetEnable">启用</el-button>
        <el-button @click="GetDeactivated">停用</el-button>
    </div>
    <!--表格-->
    <el-table :data="dictdata" style="margin-top: 10px;" @selection-change="SelectChange" ref="tableRef">
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="序号" width="70"></el-table-column>
        <el-table-column prop="position_code" label="岗位编号"></el-table-column>
        <el-table-column prop="position_name" label="岗位名称"></el-table-column>
        <el-table-column prop="position_sort" label="排序"></el-table-column>
        <el-table-column prop="position_status" label="状态">
            <template #default="scope">
                {{ scope.row.position_status === 0 ? '启用' : '停用' }}
            </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="success" text="编辑" @click="ShowUpdate(scope.row.position_id)">编辑</el-button>
                <el-button type="danger" text="删除" @click="deletePosition(scope.row.position_id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

    <!-- 添加抽屉 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">添加</h4>
        </template>
        <template #default>
            <el-form :model="addform" ref="addformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-row :gutter="20">
                    <!-- 左侧列 -->
                    <el-col :span="12">
                        <el-form-item label="岗位编号" prop="Position_code">
                            <el-input placeholder="自动获取系统编号" v-model="addform.Position_code" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="排序" prop="Position_sort">
                            <el-input placeholder="请输入" v-model="addform.Position_sort"></el-input>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 右侧列 -->
                    <el-col :span="12">
                        <el-form-item label="岗位名称" prop="Position_name">
                            <el-input placeholder="请输入" v-model="addform.Position_name"></el-input>
                        </el-form-item>
                        <el-form-item label="状态" prop="Position_status">
                            <el-radio-group v-model="addform.Position_status">
                                <el-radio :value="0">启用</el-radio>
                                <el-radio :value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 备注横跨两列 -->
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" placeholder="请输入" v-model="addform.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="Add">保存</el-button>
            </div>
        </template>
    </el-drawer>

    <!-- 修改抽屉 -->
    <el-drawer v-model="drawer2">
        <template #header>
            <h4 style="text-align: left;">修改</h4>
        </template>
        <template #default>
            <el-form :model="updateform" ref="updateformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-row :gutter="20">
                    <!-- 左侧列 -->
                    <el-col :span="12">
                        <el-form-item label="岗位编号" prop="code">
                            <el-input placeholder="自动获取系统编号" v-model="updateform.Position_code" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="排序" prop="Position_sort">
                            <el-input placeholder="请输入" v-model="updateform.Position_sort"></el-input>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 右侧列 -->
                    <el-col :span="12">
                        <el-form-item label="岗位名称" prop="Position_name">
                            <el-input placeholder="请输入" v-model="updateform.Position_name"></el-input>
                        </el-form-item>
                        <el-form-item label="状态" prop="Position_status">
                            <el-radio-group v-model="updateform.Position_status">
                                <el-radio :value="0">启用</el-radio>
                                <el-radio :value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 备注横跨两列 -->
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" placeholder="请输入" v-model="updateform.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer2 = false">取消</el-button>
                <el-button type="primary" @click="Update">保存</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox  } from 'element-plus'; //提示信息
import * as XLSX from 'xlsx';
import { useRouter } from 'vue-router';//路由
export default {
setup()
    {
        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //规则验证
        const rules = reactive({
            Position_name: [
                { required: true, message: '请输入类型名', trigger: 'blur' },
            ],
            Position_sort: [
                { required: true, message: '请输入排序', trigger: 'blur' },
                {
                    validator: (rule, value, callback) => {
                        if (value <= 0) {
                            callback(new Error('排序不能为 0 或负数'));
                        } else {
                            callback();
                        }
                    },
                    trigger: 'blur'
                }
            ]
        });

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //当前dictid
        const dictid=ref(0);


        //#region 查询

        //表单
        const dictref = ref("");
        const dictform = reactive({
            Position_code:"",
            Position_status:null
        })
        //表格数据
        const dictdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        //重置
        function Reset() {
            dictref.value?.resetFields();
            All();
        }

        //查询
        function Search() {
            currentPage.value = 1;
            All();
        }

        //查询数据
        function All() {
            http.get("/Position/GetCondition", {
                params: {
                    CurrentPage: currentPage.value,
                    Position_code:dictform.Position_code,
                    Position_name:dictform.Position_code,
                    Position_status:dictform.Position_status
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    create_time: formatDateTime(new Date(item.create_time)),
                    dict_status: item.dict_status === 0 ? '启用' : '禁用'
                }));
                dictdata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }

        //#endregion


        //#region 添加

        //添加抽屉
        const drawer = ref(false);

        const addformref = ref("");
        //添加表单
        const addform = reactive({
            Position_code:"",
            Position_name:"",
            Position_status:0,
            Position_sort:"",
            Remark:"",
        })
       
        // 添加数据
        async function Add() {
            addformref.value.validate(async (valid) => {
                if (!valid) {
                    // 验证不通过时不执行添加操作
                    ElMessage.warning('请正确填写表单');
                    return;
                }
                try {
                    // 获取自动生成编号 岗位编号为13
                    const res = await http.get("/CodeRule/GeneratedCode?id=13");
                    addform.Position_code = res.data;

                    const adddata = {
                        Position_code: addform.Position_code,
                        Position_name: addform.Position_name,
                        Position_status: addform.Position_status,
                        Position_sort: addform.Position_sort,
                        Remark: addform.Remark
                    };

                    const response = await http.post("/Position/GetAdd", adddata);

                    if (response.data > 0) {
                        ElMessage({
                            message: '添加成功.',
                            type: 'success',
                        });
                        All();
                        // 清除表单
                        addformref.value?.resetFields();
                        drawer.value=false;
                    }
                } catch (err) {
                    console.log(err);
                }
            });
        }


        //#endregion


        //#region 修改

        //修改抽屉
        const drawer2=ref(false);
        //修改表单
        const updateformref=ref("");
        const updateform = reactive({
            Position_id:0,
            Position_name:"",
            Position_status:0,
            Position_sort:"",
            Remark:"",
        })
        //显示修改
        function ShowUpdate(id){
            drawer2.value=true;
            //根据当前id查询信息
            http.get("/Position/GetID?id="+id)
            .then(res=>{
                updateform.Position_id=res.data.position_id;
                updateform.Position_name=res.data.position_name;
                updateform.Position_status=res.data.position_status;
                updateform.Position_sort=res.data.position_sort;
                updateform.remark=res.data.remark;
            }).catch(err=>{
                console.log(err);
            })
        }
        //修改
        function Update(){
            updateformref.value.validate((valid) => {
                if (!valid) {
                    // 验证不通过时不执行更新操作
                    ElMessage.warning('请正确填写表单');
                    return;
                }
                //修改数据
                const updatedata ={
                    Position_id: updateform.Position_id,
                    Position_name: updateform.Position_name,
                    Position_status: updateform.Position_status,
                    Position_sort: updateform.Position_sort,
                    remark: updateform.remark
                }
                http.put("/Position/GetEdit",updatedata)
                .then(res=>{
                    if(res.data>0){
                        ElMessage({
                            message: '修改成功.',
                            type: 'success',
                        })
                        All();
                        drawer2.value=false;
                    }
                }).catch(err=>{
                    console.log(err);
                })
            })
        }

        //#endregion 删除，启用，停用
        const tableRef = ref(null); // 添加表格引用
        // 删除方法
        function deletePosition(id) {
            ElMessageBox.confirm('确定要删除该岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await http.put('/Position/GetDelete?id='+id);
                    if (res.data && res.data.code === 1) {
                        ElMessage.success(res.data.message || '删除成功');
                        All(); // 刷新列表
                    } else if (res.data && res.data.code === 0) {
                        ElMessageBox.alert(res.data.message || '删除失败：该岗位已被其他单据引用，无法删除', '删除失败', {
                            type: 'error',
                            confirmButtonText: '确定'
                        });
                    } else if (res.data && res.data.code === -1) {
                        ElMessage.warning(res.data.message || '岗位不存在或已被删除');
                        All(); // 刷新列表
                    } else {
                        ElMessage.error('响应格式错误或未知成功状态: ' + (res.data?.message || ''));
                    }
                } catch (err) {
                    console.error("删除岗位请求失败:", err);
                    if (err.response && err.response.data) {
                        const errorData = err.response.data;
                        if (errorData.code === 0) {
                            ElMessageBox.alert(errorData.message || '删除失败：该岗位已被其他单据引用，无法删除', '删除失败', {
                                type: 'warning',
                                confirmButtonText: '确定'
                            });
                        } else if (errorData.code === -1) {
                            ElMessage.warning(errorData.message || '岗位不存在或已被删除');
                            All(); // 刷新列表
                        } else {
                            ElMessage.error('服务器错误: ' + (errorData.message || '删除请求失败'));
                        }
                    } else {
                        ElMessage.error('删除请求失败: ' + (err.message || '网络错误或服务器无响应'));
                    }
                }
            }).catch(() => {
                ElMessage.info('已取消删除');
            });
        }

        function DeleteAll() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要删除的数据');
                return;
            }
            ElMessageBox.confirm('确定要删除选中的岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    let successCount = 0;
                    let failCount = 0;
                    let messages = [];

                    for (const item of selectdata.value) {
                        try {
                            const res = await http.put(`/Position/GetDelete?id=${item.position_id}`);
                            if (res.data && res.data.code === 1) {
                                successCount++;
                            } else if (res.data && res.data.code === 0) {
                                messages.push(`岗位 ${item.position_name}: ${res.data.message || '删除失败：该岗位已被其他单据引用，无法删除'}`);
                                failCount++;
                            } else if (res.data && res.data.code === -1) {
                                messages.push(`岗位 ${item.position_name}: ${res.data.message || '岗位不存在或已被删除'}`);
                                failCount++;
                            } else {
                                messages.push(`岗位 ${item.position_name}: 响应异常 (${res.data?.message || '未知错误'})`);
                                failCount++;
                            }
                        } catch (err) {
                            failCount++;
                            let errorMsg = `请求失败`;
                            if (err.response && err.response.data && err.response.data.message) {
                                if (err.response.data.code === 0) {
                                    errorMsg = err.response.data.message;
                                } else {
                                    errorMsg = err.response.data.message;
                                }
                            } else if (err.message) {
                                errorMsg = err.message;
                            }
                            messages.push(`岗位 ${item.position_name}: ${errorMsg}`);
                            console.error(`删除岗位 ${item.position_name} 失败:`, err);
                        }
                    }
                    if (successCount > 0) {
                        ElMessage.success(`成功删除 ${successCount} 条数据`);
                    }
                    if (failCount > 0) {
                        const combinedMessage = messages.length > 3 ?
                        `${messages.slice(0, 3).join('<br>')}<br>...(还有 ${messages.length - 3} 条错误)` :
                            messages.join('<br>');
                        const hasReferenceError = messages.some(msg => msg.includes('引用'));

                        ElMessageBox.alert(combinedMessage, `删除结果 (${successCount} 成功, ${failCount} 失败)`, {
                            type: hasReferenceError ? 'warning' : 'error',
                            confirmButtonText: '确定',
                            dangerouslyUseHTMLString: true,
                            customClass: 'scrollable-alert'
                        })
                    }

                    All();
                    tableRef.value.clearSelection();
                } catch (err) {
                    console.error("批量删除过程中发生未预期的错误:", err);
                    ElMessage.error('批量删除过程出错: ' + (err.message || ''));
                }
            }).catch(() => {
                ElMessage.info('已取消批量删除');
            });
        }
        
        // 批量停用
        function GetDeactivated() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要停用的数据');
                return;
            }
            
            ElMessageBox.confirm('确定要停用选中的岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deletePromises = selectdata.value.map(item => {
                    return http.put(`/Position/GetDeactivated?id=${item.position_id}`);
                });
                
                Promise.all(deletePromises)
                    .then(results => {
                        const successCount = results.filter(res => res.data > 0).length;
                        if (successCount === selectdata.value.length) {
                            ElMessage.success(`成功停用 ${successCount} 条数据`);
                        } else {
                            ElMessage.warning(`成功停用 ${successCount} 条，失败 ${selectdata.value.length - successCount} 条`);
                        }
                        All(); // 刷新数据
                        tableRef.value.clearSelection(); // 清空选中状态
                    })
                    .catch(err => {
                        console.error(err);
                        ElMessage.error('停用失败');
                    });
            }).catch(() => {
                ElMessage.warning('已取消停用');
                return;
            });
        }
        
        // 批量启用
        function GetEnable() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要启用的数据');
                return;
            }
            
            ElMessageBox.confirm('确定要启用选中的岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deletePromises = selectdata.value.map(item => {
                    return http.put(`/Position/GetEnable?id=${item.position_id}`);
                });
                
                Promise.all(deletePromises)
                    .then(results => {
                        const successCount = results.filter(res => res.data > 0).length;
                        if (successCount === selectdata.value.length) {
                            ElMessage.success(`成功启用 ${successCount} 条数据`);
                        } else {
                            ElMessage.warning(`成功启用 ${successCount} 条，失败 ${selectdata.value.length - successCount} 条`);
                        }
                        All(); // 刷新数据
                        tableRef.value.clearSelection(); // 清空选中状态
                    })
                    .catch(err => {
                        console.error(err);
                        ElMessage.error('启用失败');
                    });
            }).catch(() => {
                ElMessage.warning('已取消启用');
                return;
            });
        }
        //#endregion


        //点击列表跳转
        function ShowInfo(id){
            //传当前对应字典类型Id过去
            router.push({
                name:"dictdata",
                params:{
                    dicttypeid:id,
                }
            })
        }


        //挂载
        onMounted(() => {
            All();
        });


        return{
            GetDeactivated,
            GetEnable,
            tableRef,
            deletePosition,
            DeleteAll,
            SelectChange,
            formatDateTime,
            user,
            dictid,
            dictref,
            dictform,
            dictdata,
            rows,
            currentPage,
            dateFormat,
            Reset,
            Search,
            All,
            handlePageChange,
            drawer,
            addform,
            addformref,
            Add,
            rules,
            drawer2,
            updateform,
            updateformref,
            ShowUpdate,
            Update,
            DeleteAll,
            router,
            ShowInfo
        }

    }
}
</script>

<style scoped>

</style>